package com.yu.Controller;


import com.yu.POJO.Admin;
import com.yu.POJO.Notice;
import com.yu.POJO.Student;
import com.yu.POJO.Teacher;
import com.yu.Service.teaService;
import com.yu.tool.MyJson;
import com.yu.tool.Validate;
import com.yu.Service.AdminService;
import com.yu.Service.StuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 *
 * @Author: LittleFisher
 * @Date: 2021/05/23/16:03
 * @Description:
 */
@Controller
public class LoginController {
    @Autowired
    StuService stuService;

    @Autowired
    AdminService adminService;

    @Autowired
    teaService teaService;

    private static String uploadPath = "E:" + File.separator;

    /**
     *
     * to登录页面
     */
    @RequestMapping("/login")
    public String login(){
        return "login";
    }


    /**
     *  登录验证
     * @param name 账号或者学号
     * @param vCode 验证码
     * @param password 密码
     * @param session
     * @return
     */
    @RequestMapping("/adminLogin")
    public String adminLogin(@RequestParam String name,@RequestParam String vCode, @RequestParam String password, HttpSession session){
        String msg = "";
        MyJson myJson = adminService.adminLogin(name,password);
        String sessionVCode = (String) session.getAttribute("vcode");
        if (sessionVCode.equals(vCode)){
            if(myJson.getMsg()){
                Admin admin = adminService.getAdminByName(name);
                session.setAttribute("admin", admin);

                //通告加载
                List<Notice> list = adminService.getAllNotice();
                session.setAttribute("notices", list);
                return "admin/Admin";
            }
            else {
                msg += myJson.getError()+",请重新输入!";
                session.setAttribute("msg", msg);
                return "login";
            }
        }else {
            msg += "验证码错误,请重新输入!";
            session.setAttribute("msg", msg);
            return "login";
        }
    }

    @RequestMapping("/stuLogin")
    public String stuLogin(@RequestParam String name,@RequestParam String vCode, @RequestParam String password, HttpSession session){
        String msg = "";
        MyJson myJson = stuService.stuLogin(name,password);
        String sessionVCode = (String) session.getAttribute("vcode");
        if (sessionVCode.equals(vCode)){
            if(myJson.getMsg()){
                //学生保存在session 中
                Student stu = stuService.findStuBySno(name);
                session.setAttribute("stu",stu);

                //通告加载
                List<Notice> list = adminService.getAllNotice();
                session.setAttribute("notices", list);
                return "stu/Student";
            }
            else {
                msg += myJson.getError()+",请重新输入!";
                session.setAttribute("msg", msg);
                return "login";
            }
        }else {
            msg += "验证码错误,请重新输入!";
            session.setAttribute("msg", msg);
            return "login";
        }

    }

    @RequestMapping("teaLogin")
    public String teaLogin(@RequestParam String name, @RequestParam String vCode,@RequestParam String password, HttpSession session) throws ServletException, IOException{
        String msg = "";
        MyJson myJson = teaService.teaLogin(name,password);
        String sessionVCode = (String) session.getAttribute("vcode");
        if (sessionVCode.equals(vCode)){
            if(myJson.getMsg()){
                //学生保存在session 中
                Teacher tea = teaService.findTeaByName(name);
                session.setAttribute("tea", tea);

                //通告加载
                List<Notice> list = adminService.getAllNotice();
                session.setAttribute("notices", list);
                return "tea/teacher";
            }
            else {
                msg += myJson.getError()+",请重新输入!";
                session.setAttribute("msg", msg);
                return "login";
            }
        }else {
            msg += "验证码错误,请重新输入!";
            session.setAttribute("msg", msg);
            return "login";
        }
    }

    /**
     * 用户登出
     * @param session session 移除
     * @return
     */
    @RequestMapping("/loginOut")
    public String loginOut(HttpSession session){
        session.invalidate();
        return "redirect:login";
    }


    /**
     * 验证码
     * @param request
     * @param response
     * @param session
     * @throws IOException
     */
    @RequestMapping("/getVCode")
    private void getVCode(HttpServletRequest request, HttpServletResponse response,HttpSession session) throws IOException {
        Validate validate =new Validate();
        String vcode = validate.getCode();
        session.setAttribute("vcode", vcode);
        response.setHeader("Pragma","No-cache");
        response.setHeader("Cache-Control","no-cache");
        ImageIO.write(validate.getImage(vcode), "JPEG", response.getOutputStream());//输出图片到页面
    }

    /**
     * 文件上传
     * @param multipartFile 上传的文件对象
     * @param model
     * @return
     */
    @RequestMapping("/upload")
    public String upload(@RequestParam("file") MultipartFile multipartFile, Model model) {
        //1、传到哪里去  2、我传什么东西  3、传的细节

        //1、判断
        if (multipartFile != null && !multipartFile.isEmpty()) {
            //不空才传
            //2、获取原始文件名
            String originalFilename = multipartFile.getOriginalFilename();

            //3、 先截取原文件的文件名前缀，不带后缀
            String fileNamePrefix=originalFilename.substring(0,originalFilename.lastIndexOf("."));

            //4、加工处理文件名，将原文件+时间戳
            String newFileNamePrefix=fileNamePrefix+new Date().getTime();

            //5、得到新文件名
            String newFileName=newFileNamePrefix+originalFilename.substring(originalFilename.lastIndexOf("."));

            //6、构建文件对象
            File file=new File(uploadPath+newFileName);

            //7、上传
            try {
                multipartFile.transferTo(file);
                model.addAttribute("fileName",newFileName);
            }catch (IOException e){
                e.printStackTrace();
            }

        }
        return "Success";
    }

    @RequestMapping("getNewsById")
    @ResponseBody
    public Notice getNewsById(int id){
        return adminService.getNewsById(id);
    }
}
